﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Club.Helpers;
using DAL;
using Util;

namespace Club.Controllers
{
    public class UserController : Controller
    {
        //
        // GET: /User/

        public ActionResult List()
        {
            Dictionary<string, object> sessionVar = (Dictionary<string, object>)Session["vars"];
            DAL.User user = (DAL.User)sessionVar["userVar"];
            if (user == null)
            {
                Response.Redirect("/Default.aspx?prepage=/User/List/");
                return null;
            }
            if (user.RoleId != (short)ROLE_ENUM.ADMIN)
            {
                Response.Redirect("/AccessDenied.aspx");
                return null;
            }
            DAL.User l_user=new DAL.User();
            List<DAL.User> l_users = l_user.getUsers();            
            string sortExpr = !string.IsNullOrEmpty(GetString("SortExpr")) ? GetString("SortExpr") : "ID";
            string sortDir = !string.IsNullOrEmpty(GetString("SortDir")) ? GetString("SortDir") : "ASC";
            int pageNumber = GetInt("Page");           

            if (sortExpr.Equals("FullName"))
                l_users.Sort(SortByFullName);
            else if (sortExpr.Equals("Email"))
                l_users.Sort(SortByEmail);
            else if (sortExpr.Equals("LoginID"))
                l_users.Sort(SortByLoginID);
            else
                l_users.Sort(SortByID);

            if (sortDir.Equals("DESC"))
                l_users.Reverse();

            int s_index = pageNumber * Util.CoreConstant.PAGE_SIZE;
            int countPerpage = Util.CoreConstant.PAGE_SIZE;

            s_index = s_index > 0 ? s_index - 1 : s_index;
            if (s_index + countPerpage > l_users.Count)
                countPerpage = l_users.Count - s_index;

            Models.UsersModel l_usersModel = new Models.UsersModel();
            l_usersModel.Users = l_users.GetRange(s_index,countPerpage);
            l_usersModel.UserCount = l_user.getUserCount();
            ViewData.Model = l_usersModel;
            return View();
        }

        public ActionResult Manage(int id)
        {
            Dictionary<string, object> sessionVar = (Dictionary<string, object>)Session["vars"];
            DAL.User user = (DAL.User)sessionVar["userVar"];
            if (user == null)
            {
                Response.Redirect("/Default.aspx?prepage=/User/Manage/" + id);
                return null;
            }
            if (user.RoleId != (short)ROLE_ENUM.ADMIN)
            {
                Response.Redirect("/AccessDenied.aspx");
                return null;
            }
            DAL.User l_user = new DAL.User().getUserById(id);
            ViewData.Model = l_user;
            ViewData["Roles"] = new SelectList(new BLL.ValidateUser().getRoles());
            return View();
        }

        [HttpParamAction]
        [HttpPost]
        public ActionResult Update(int id,User aCol,FormCollection aFormCol)
        {
            Dictionary<string, object> sessionVar = (Dictionary<string, object>)Session["vars"];
            DAL.User user = (DAL.User)sessionVar["userVar"];
            if (user == null)
            {
                Response.Redirect("/Default.aspx?prepage=/User/Manage/" + id);
                return null;
            }
            if (user.RoleId != (short)ROLE_ENUM.ADMIN)
            {
                Response.Redirect("/AccessDenied.aspx");
                return null;
            }
            try
            {
                 DAL.ClubEntities l_entity = new DAL.ClubEntities();
                var tmp = l_entity.Users.First(m => m.Id == (short)id);
                if (tmp != null)
                {
                    tmp.Email = aCol.Email.ToString();
                    tmp.FullName = aCol.FullName.ToString();
                    tmp.Name = aCol.Name.ToString();
                    if (aFormCol["chkAdministrator"].ToString().StartsWith("true"))
                    {
                        tmp.RoleId = 1;
                    }
                    else
                    {
                        tmp.RoleId = 2;
                    }
                }
                l_entity.SaveChanges();
                ViewData["Update"] = "Success";
                return View("Manage",tmp);
            }
            catch (Exception ex)
            {
                ViewData["Update"] = ex.Message;
                return RedirectToAction("Manage", "User", new { id = id });
            }                       
        }

        [HttpParamAction]
        [HttpPost]
        public ActionResult ResetPassword(int id)
        {
            Dictionary<string, object> sessionVar = (Dictionary<string, object>)Session["vars"];
            DAL.User user = (DAL.User)sessionVar["userVar"];
            if (user == null)
            {
                Response.Redirect("/Default.aspx?prepage=/User/ResetPassword/" + id);
                return null;
            }
            if (user.RoleId != (short)ROLE_ENUM.ADMIN)
            {
                Response.Redirect("/AccessDenied.aspx");
                return null;
            }
            DAL.User l_user = new DAL.User();
            if (l_user.resetPassword(id))
            {
                ViewData["ResetPwd"] = "Success";
            }
            else
            {
                ViewData["ResetPwd"] = "Fail";
            }
            
            return View();
        }

        private static int SortByFullName(DAL.User first, DAL.User second)
        {
            if (first.FullName == null)
            {
                if (second.FullName == null)
                {
                    return 0;
                }
                else
                {
                    return -1;
                }
            }
            else
            {
                if (second.FullName == null)
                {
                    return 1;
                }
                else
                {
                    return first.FullName.CompareTo(second.FullName);
                }
            }
        }

        private static int SortByEmail(DAL.User first, DAL.User second)
        {
            if (first.Email == null)
            {
                if (second.Email == null)
                {
                    return 0;
                }
                else
                {
                    return -1;
                }
            }
            else
            {
                if (second.Email == null)
                {
                    return 1;
                }
                else
                {
                    return first.Email.CompareTo(second.Email);
                }
            }
        }

        private static int SortByLoginID(DAL.User first, DAL.User second)
        {
            if (first.Name == null)
            {
                if (second.Name == null)
                {
                    return 0;
                }
                else
                {
                    return -1;
                }
            }
            else
            {
                if (second.Name == null)
                {
                    return 1;
                }
                else
                {
                    return first.Name.CompareTo(second.Name);
                }
            }
        }

        private static int SortByID(DAL.User first, DAL.User second)
        {
            if (first.Id == null)
            {
                if (second.Id == null)
                {
                    return 0;
                }
                else
                {
                    return -1;
                }
            }
            else
            {
                if (second.Id == null)
                {
                    return 1;
                }
                else
                {
                    return first.Id.CompareTo(second.Id);
                }
            }
        }                

        private string GetString(string s)
        {
            return HttpUtility.UrlDecode(this.ControllerContext.HttpContext.Request.QueryString[s]);
        }

        private int GetInt(string s)
        {
            int id;
            if (int.TryParse(HttpUtility.UrlDecode(this.ControllerContext.HttpContext.Request.QueryString[s]), out id))
            {
                return id;
            }

            // if an error, return 0
            return 0;
        }

    }
}
